package com.adgox.tiantianbiting.mine.TingCoinWithdraw;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.utils.ApiConstant;
import com.adgox.tiantianbiting.utils.DialogUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rae.swift.session.SessionManager;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TingCoinWithdrawActivity extends AppCompatActivity implements TingCoinWithdrawContract.View, View.OnClickListener {

    @BindView(R.id.et_withdraw_amount)
    EditText etWithdrawAmount;
    @BindView(R.id.tv_withdraw)
    TextView tvWithdraw;
    private int userId;
    private double commission;
    private TextView etName;
    private TextView etMobile;
    private EditText etVert;
    private TextView tvSendVert;
    private Dialog dialog;
    private String mobile;
    private TingCoinWithdrawContract.Presenter mPresenter;
    private int vertifyCD;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ting_coin_withdraw);
        ButterKnife.bind(this);
        new TingCoinWithdrawPresenterImpl(this);
        UserInfo userInfo = (UserInfo) SessionManager.getDefault().getUser();
        userId = userInfo.getId();
        commission = userInfo.getCommission();

        SpannableString ss = new SpannableString("可提现金额" + commission + "元");
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(11, true);
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        etWithdrawAmount.setHint(new SpannableString(ss));

        etWithdrawAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!s.toString().trim().isEmpty()) {
                    tvWithdraw.setBackgroundColor(Color.parseColor("#fe9020"));

                    double et = Double.parseDouble(s.toString());
                    if (commission >= 7) {
                        if (et > 7) {
                            etWithdrawAmount.setText("7");
                            Toast.makeText(TingCoinWithdrawActivity.this, "单次提现金额不可大于7元", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        if (et > commission) {
                            etWithdrawAmount.setText(commission + "");
                        }
                    }
                } else {
                    tvWithdraw.setBackgroundColor(Color.parseColor("#aeaeae"));
                }
                CharSequence text = etWithdrawAmount.getText();
                if (text instanceof Spannable) {
                    Spannable spantext = (Spannable) text;
                    Selection.setSelection(spantext, text.length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //提现
    @OnClick(R.id.tv_withdraw)
    public void onWithdrawClicked() {
//        Intent intent = new Intent(this, WebviewActivity.class);
//        intent.putExtra("url","http://192.168.1.196:8085/ttbt_act_h5/index.html");
//        startActivity(intent);
        if (commission <= 0) {
            Toast.makeText(this, "没有可提现的金额", Toast.LENGTH_SHORT).show();
            return;
        }
        popCheckDialog();
    }

    private void popCheckDialog() {
        dialog = new Dialog(this);
        Window window = dialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setContentView(R.layout.layout_withdraw_check_dialog);
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.BOTTOM);
        window.setDimAmount(0.8f);
        ImageView ivCancel = dialog.findViewById(R.id.iv_cancel);
        etName = dialog.findViewById(R.id.et_name);
        etMobile = dialog.findViewById(R.id.et_phone);
        etVert = dialog.findViewById(R.id.et_vert);
        tvSendVert = dialog.findViewById(R.id.tv_send_vert);
        TextView tvCommit = dialog.findViewById(R.id.tv_commit);

        ivCancel.setOnClickListener(this);
        tvSendVert.setOnClickListener(this);
        tvCommit.setOnClickListener(this);
        dialog.show();
    }

    @OnClick(R.id.img_finish)
    public void onFinishClicked() {
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_cancel:
                dialog.dismiss();
                break;
            case R.id.tv_send_vert:
                //点击发送验证码
                sendVert();
                break;
            case R.id.tv_commit:
                //验证并提交
                checkVertAndCommit();
                break;
        }
    }

    private void checkVertAndCommit() {
        if (mobile == null || !mobile.equals(etMobile.getText().toString().trim())) {
            Toast.makeText(this, "手机号为空或前后不一致", Toast.LENGTH_SHORT).show();
            return;
        }
        if (etVert.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "验证码不可为空", Toast.LENGTH_SHORT).show();
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("mobile", etMobile.getText().toString().trim());
        map.put("name", etName.getText().toString().trim());
        map.put("userId", userId);
        map.put("verCode", etVert.getText().toString().trim());
        Gson gson = new Gson();
        String s = gson.toJson(map);
        DialogUtils.showLoadingDialog(this);
        mPresenter.checkVert(s);
    }

    private void sendVert() {
        if (etName.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "姓名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (etMobile.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!etMobile.getText().toString().trim().matches("[1]\\d{10}")) {
            Toast.makeText(this, "手机号格式不对", Toast.LENGTH_SHORT).show();
            return;
        }
        mobile = etMobile.getText().toString().trim();
        DialogUtils.showLoadingDialog(this);
        mPresenter.sendVert(mobile, userId);
    }

    @Override
    public void setPresenter(TingCoinWithdrawContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void onGetVertSuccess() {
        Toast.makeText(this, "获取验证码成功", Toast.LENGTH_SHORT).show();
        tvSendVert.setClickable(false);
        vertifyCD = 60;
        handler.post(runnable);
    }

    @Override
    public void onGetVertFailed(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCheckVertSuccess() {
        dialog.dismiss();
        sendWithDrawRequest();
    }

    private void sendWithDrawRequest() {
        String amount = etWithdrawAmount.getText().toString().trim();
        OkGo.<BaseResponseBean<String>>post(ApiConstant.BASE_URL + ApiConstant.WITHDRAW + userId + "/0/" + amount)
                .execute(new JsonCallback<BaseResponseBean<String>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<String>> response) {
                        if ("0".equals(response.body().getCode())) {
                            Toast.makeText(TingCoinWithdrawActivity.this, "提现申请提交成功，请等待审核", Toast.LENGTH_SHORT).show();
                        } else if ("022".equals(response.body().getCode())) {
                            Toast.makeText(TingCoinWithdrawActivity.this, "用户不是超级会员不能申请提现", Toast.LENGTH_SHORT).show();
                        } else if ("089".equals(response.body().getCode())) {
                            Toast.makeText(TingCoinWithdrawActivity.this, "可提现金额必须小于等于余额", Toast.LENGTH_SHORT).show();
                        } else if ("081".equals(response.body().getCode())) {
                            Toast.makeText(TingCoinWithdrawActivity.this, "佣金账户不够", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(TingCoinWithdrawActivity.this, "提现申请提交失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    public void onCheckVertFailed(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            vertifyCD--;
            tvSendVert.setText(vertifyCD + "s");
            if (vertifyCD == 0) {
                tvSendVert.setText("点击获取");
                tvSendVert.setClickable(true);
                handler.removeCallbacks(runnable);
            } else {
                handler.postDelayed(runnable, 1000);
            }
        }
    };
}
